import React, { useCallback } from 'react';
import { Form, Button, Input, Selector, Toast } from 'antd-mobile';
import Channels from '../shared/Channels';
import Requests from '../shared/RestUtils';
import { useHistory } from 'react-router';

function SignIn() {
    const history = useHistory();

    const onFinished = useCallback(
        async ({ name, password, channel }) => {
            try {
                const result = await Requests.env(channel[0]).login(name, password);
                localStorage.setItem('auth-token', result.token);
                localStorage.setItem('channel', result.channel);

                history.replace('/');
            }
            catch (ex) {
                Toast.show({
                    icon: 'fail',
                    content: ex.response.data,
                    position: 'top'
                });
            }
        }, [history],
    )

    return (
        <>
            <h1 className="title">Kids Console Admin</h1>
            <div>
                <Form
                    footer={
                        <Button block type='submit' color='primary'>
                            Login
                        </Button>
                    }
                    onFinish={onFinished}
                >
                    <Form.Item name='name' label='Name'
                        rules={[{ required: true, message: 'Name is required' }]}>
                        <Input placeholder='Please input admin name' />
                    </Form.Item>
                    <Form.Item name='password' label='Password'
                        rules={[{ required: true, message: 'Name is required' }]}>
                        <Input placeholder='Please input password' type="password" />
                    </Form.Item>
                    <Form.Item name='channel' label='Channel' initialValue={['prod']}
                        rules={[{ required: true, message: 'Name is required' }]}>
                        <Selector options={Channels} />
                    </Form.Item>
                </Form>
            </div>
        </>
    );
}

export default SignIn;